package com.lagou.task19;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class Sendtest {
    public static void main(String[] args) {
        DatagramSocket datagramSocket = null;
        try {
//        1创建DataGramSocket对象
            datagramSocket = new DatagramSocket();
//        2创建DataGramPacket对象并提供接收方的通信地址和端口号
            byte[] b1 = "hello".getBytes();
            DatagramPacket datagramPacket = new DatagramPacket(b1,b1.length, InetAddress.getLocalHost(),8888);
//        3通过Socket发送Packet
            datagramSocket.send(datagramPacket);

            //接收消息
            byte[] arr = new byte[20];
            DatagramPacket datagramPacket1 = new DatagramPacket(arr,arr.length);
            datagramSocket.receive(datagramPacket1);
            String s1 = new String(arr,0,datagramPacket1.getLength());
            System.out.println("收到回复" + s1);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //        4关闭Socket
            if (datagramSocket != null) {
                datagramSocket.close();
            }
        }


    }
}
